package com.wolfeyes.framework.springsecurity.handle;

//import com.wolfeyes.common.constant.FilmSystemConstants;
import com.wolfeyes.common.constant.HttpStatusConstants;
import com.wolfeyes.common.response.ResponseResult;
import com.wolfeyes.framework.springsecurity.domain.model.CustomizeUserDetails;

import lombok.extern.slf4j.Slf4j;

import com.wolfeyes.common.utils.network.http.ServletUtils;
import com.wolfeyes.common.utils.character.StringUtils;
//import com.wolfeyes.core.manager.AsyncManager;
//import com.wolfeyes.core.manager.factory.AsyncFactory;
import com.wolfeyes.framework.service.TokenService;
import com.alibaba.fastjson.JSON;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description SpringSecurity安全认证权限框架
 * @see Talk is cheap, Show me the code. -- Linus Torvalds
 * @title 自定义的登出注销（成功）处理器
 * @author yanyljava
 * @create 2022-01-14 21:25
 */
@Slf4j
@Configuration
public class CustomizeLogoutSuccessHandler implements LogoutSuccessHandler {
	
	@Autowired
	private TokenService tokenService;

	/**
	 * @title 登出注销（成功）处理逻辑
	 * @description 登出注销（成功）的时候调用，Jwt有个缺点就是无法主动控制失效，可以采用Jwt+session的方式，比如删除存储在Redis的token
	 * @description 请注意，如果将SpringSecurity的session配置为无状态，或者不保存session，这里authentication为null！！，注意空指针问题
	 */
	@Override
	public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

		log.debug("自定义的登出注销（成功）处理器被调用 Start！");
		CustomizeUserDetails customizeUserDetails = tokenService.getCustomizeUserDetails(httpServletRequest);
		
		if (StringUtils.isNotNull(customizeUserDetails)) {
			//String userName = customizeUserDetails.getUsername();
			// 删除用户缓存记录
			tokenService.delCustomizeUserDetails(customizeUserDetails.getToken());
			// 记录用户退出日志 异步任务模式
			//AsyncManager.me().execute(AsyncFactory.recordLoginInfor(userName, Constants.LOGOUT, "退出成功"));
		}
		// Logout Success 
		ServletUtils.renderString(httpServletResponse, JSON.toJSONString(ResponseResult.error(HttpStatusConstants.SUCCESS, "退出成功")));

		log.debug("自定义的登出注销（成功）处理器被调用 End！");
	}
	
}


